package actions;

import java.sql.SQLException;

import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.UserModel;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import db.DBModel;

public class BanFromEventAction extends Action{
	public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request,HttpServletResponse response){
		try {
			String userIdFromRequest=request.getParameter("id");
			String eventIdFromRequest=request.getParameter("eventId");
			int userIdToBan=0;
			int eventId=-1;
			if(userIdFromRequest!=null){
				userIdToBan=Integer.parseInt(userIdFromRequest);
			}
			if(eventIdFromRequest!=null){
				eventId=Integer.parseInt(eventIdFromRequest);
			}
			if(userIdToBan==0){
				return new ActionForward(mapping.findForward("invalidId").getPath()+"?id=eventId");
			}
			
			DBModel db=new DBModel();
			String currentUserName=request.getUserPrincipal().getName();
			System.out.println("dette er brukeren"+currentUserName);
			UserModel owner=db.getEventOwner(eventId);
			if(owner.getId()==userIdToBan){
				request.setAttribute("banYourSelf", owner);
				return new ActionForward(mapping.findForward("success").getPath()+"?id="+eventId);
			}
			if(currentUserName.equalsIgnoreCase(owner.getUsername()))
			{
				db.banUserFromEvent(eventId,userIdToBan);
				db.close();
				return new ActionForward(mapping.findForward("success").getPath()+"?id="+eventId);
			}
			db.close();
		} catch (Exception e){
			e.printStackTrace();
			request.setAttribute("error", e.toString());
			return mapping.findForward("fail");
		}	
		return mapping.findForward("fail");
	}
}
